package com.server.commons.security.Aspect;


import com.server.common.code.error.PreAuthorizeException;
import com.server.common.code.utils.UserUtils;
import com.server.common.code.vo.LoginVo;
import com.server.common.security.code.SecurityUtils;
import com.server.common.security.code.anntation.PreAuthorize;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Method;

@Aspect
@Component
public class PreAuthorizeAspect {

    @Around("@annotation(com.server.common.security.code.anntation.PreAuthorize)")
    public Object around(ProceedingJoinPoint point) throws Throwable {

        Signature signature = point.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        PreAuthorize preAuthorize = method.getAnnotation(PreAuthorize.class);

        //不需要权限认证
        if(ObjectUtils.isEmpty(preAuthorize)){
            return point.proceed();
        }

        LoginVo loginVo = SecurityUtils.getLoginVo();

        //当前用户是admin
        if(UserUtils.haveAdmin(loginVo.getRoleId())){
            return point.proceed();
        }

        //权限为空
        if(ObjectUtils.isEmpty(loginVo.getPreAuths())){
            throw new PreAuthorizeException();
        }

        //是否存在
        if(!loginVo.getPreAuths().contains(preAuthorize.hasPre())){
            throw new PreAuthorizeException();
        }

        return point.proceed();
    }
}
